#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 10/19/2019 10:28 PM

# !usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 7/30/2019 10:05 AM


from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


# TODO use generic name of paginator
def get_paginated(request, object_list, page_count):
    # page_count ·每页显示的文章数量
    # left_dot 左边是否显示省略号 right_dot same
    # page_num 当前请求的页码 == current_page
    # object_page_list 当前请求页的对象
    paginator = Paginator(object_list, page_count)
    try:
        page_num = int(request.GET.get('page', 1))
        # when get a page number is biger than total pages or less than 0 set page num 1
        if page_num > paginator.num_pages or page_num < 0:
            page_num = 1
    except PageNotAnInteger:
        page_num = 1
    except EmptyPage:
        page_num = paginator.num_pages

    def get_pages(paginator, page_num, left_dot=False, right_dot=False):
        # current_page: current page num
        # page_range: All page ranges
        current_page = int(page_num)
        page_range = list(paginator.page_range)
        first_page_num = page_range[0]
        last_page_num = page_range[-1]

        if page_range[-1] <= 7:
            pages = list(page_range)
        else:
            # 获取当前页面右侧页码
            if current_page + 5 < last_page_num:
                right_dot = True
                right_pages = page_range[current_page - 1:current_page + 2] + [last_page_num, ]  # include current page
            else:
                right_pages = page_range[current_page - 1:]  # include current page
            # 获取当前页面左侧页码
            if current_page - 5 > first_page_num:
                left_dot = True
                left_pages = [first_page_num, ] + page_range[current_page - 4:current_page - 1]
            else:
                left_pages = page_range[:current_page - 1]
            pages = left_pages + right_pages
        # 因为首页和尾页始终显示，所以在生成页码时将首页，发尾页去年
        pages = pages[1:-1]
        return pages, right_dot, left_dot

    pages, right_dot, left_dot = get_pages(paginator, page_num)
    page_obj_list = paginator.page(page_num)
    context = {
        'current_page': page_num,
        'cur_page_objects': page_obj_list,
        'pages': pages,
        'last_page': paginator.num_pages,
        'first_page': 1,
        'left_dot': left_dot,
        'right_dot': right_dot
    }
    return context
